import { Tools } from './../../../../tools/tools';
import { Subscription } from 'rxjs';
import { MessageService } from './../../../../../services/message.service';
import { Component, OnInit, OnDestroy } from '@angular/core';
import * as dayjs from 'dayjs';
import { NzMessageService } from 'ng-zorro-antd';
import { BaseService, DataRegisterService, WorkflowService } from 'src/app/services';
import { EventManagerService } from 'src/app/services/event-manager.service';
import { OrganizationService } from 'src/app/services/organization.service';
import { UploadService } from 'src/app/services/upload.service';
import { EngineService } from '../../../services/engine.service';
import { BaseFieldComponent } from '../base-field/base-field.component';
import { Message } from 'src/app/models/message';
import { PermitItem } from 'src/app/models/permitItem';
import { Md5 } from 'ts-md5';
import { WorkflowPageService } from 'src/app/common/page-render/workflow-page-container/workflow-page.service';
import { DataRegister } from 'src/app/models/data-register';
import * as Enumerable from 'linq';
import { PersonnelService } from 'src/app/services/personnel.service';

@Component({
  selector: 'zepride-early-warning',
  templateUrl: './early-warning.component.html',
  styleUrls: ['./early-warning.component.less']
})
export class EarlyWarningComponent extends BaseFieldComponent implements OnInit, OnDestroy {
  workflowUpdatedSub: Subscription;
  spaceChars: SpaceCharItem[] = [];
  involvedPersonChangeSub: Subscription;
  userIds: string[] = [];
  dataRegister: DataRegister;

  constructor(
    protected engineService: EngineService,
    protected baseSvr: BaseService,
    protected eventSvr: EventManagerService,
    protected orgSvr: OrganizationService,
    public uploadService: UploadService,
    protected msg: NzMessageService,
    protected messageSvr: MessageService,
    protected workflowSvr: WorkflowService,
    private wSvr: WorkflowPageService,
    protected dataRegisterService: DataRegisterService,
    private userSvr: PersonnelService
  ) {

    super(engineService, baseSvr, eventSvr, orgSvr, uploadService, msg, dataRegisterService);
  }
  ngOnDestroy(): void {
    if (this.involvedPersonChangeSub) {
      this.involvedPersonChangeSub.unsubscribe();
    }
    if (this.workflowUpdatedSub) {
      this.workflowUpdatedSub.unsubscribe();
    }
  }

  ngOnInit(): void {
    this.spaceChars = this.componentData.extends.spaceChars;

    this.engineService.componentHide$.next({
      tmpComItemId: this.tmpComItemId
    });

    this.involvedPersonChangeSub = this.workflowSvr.involvedPersonChange$.subscribe((data: { permitList: PermitItem[]; userId: string; }[]) => {
      this.userIds = data.map(x => x.userId);
    });

    this.workflowUpdatedSub = this.wSvr.workflowUpdated.subscribe(async data => {
      if (!data) {
        return;
      }

      this.dataRegister = data;
    });
  }

  generateMessageTxt() {
    const txt = this.replaceTxt();
  }

  private async replaceTxt() {
    let txt: string = this.componentData.extends.txtAreaContent;
    for (const item of this.spaceChars) {
      if (item.selector == 'single-date' || item.selector == 'single-date-cur') {
        // 如果选择的是时间组件或者选择的是当前时间
        let dateObject = this.dataModel[item.bindField];
        if (item.selector == 'single-date-cur') {
          dateObject = {
            date: new Date(),
            ts: Date.now()
          };
          dateObject.display = dayjs(dateObject.ts).format('YYYY-MM-DD HH:mm');
        }
        if (!dateObject || !dateObject.date) {
          continue;
        }
        let repTxt = dateObject.display;
        if (item.addTime) {
          if (item.addTimeType == 'normalDay') {
            repTxt = dayjs(dateObject.ts).add(item.addTime, 'day').format('YYYY-MM-DD HH:mm');
          }
          else if (item.addTimeType == 'workDay') {
            repTxt = await this.messageSvr.getAfterWorkdayDate({
              fromDay: dayjs(dateObject.ts).format('YYYY-MM-DD HH:mm'),
              days: item.addTime
            });
          }
          else if (item.addTimeType == 'minutes') {
            repTxt = dayjs(dateObject.ts).add(item.addTime, 'minute').format('YYYY-MM-DD HH:mm');
          }
        }

        txt = txt.replace(item.code, repTxt);
      }
      else {
        let repTxt = this.dataModel[item.bindField];
        repTxt || (repTxt = '【】');
        txt = txt.replace(item.code, repTxt);
      }

    }

    return txt;
  }

  pageSavedHandle = async () => {
    const msgBody = await this.replaceTxt();
    const orgId = localStorage.getItem('orgid');
    const userInfo = JSON.parse(localStorage.getItem('userInfo'));
    const curWf = this.workflowSvr.currentWorkflow;

    this.userIds || (this.userIds = []);

    if (this.userIds.length == 0) {
      //如果没有选择项目成员，通知到所有的用户
      const result = await this.userSvr.queryUsers({});
      this.userIds = result.list.map(x => x.id);
    }
    else {
      this.userIds.push(userInfo.id);
    }

    this.userIds = Enumerable.from(this.userIds).distinct().toArray();

    let messageObj: Message = {
      id: '',
      name: '',
      title: '',
      body: msgBody,
      type: this.componentData.extends.msgType,
      orgId,
      senderId: userInfo.id,
      sender: userInfo,
      objectId: curWf.id,
      objectType: 'Workflow',
      receiverIds: this.userIds,
      dataRegisterId: this.dataRegister.id
    };

    if (this.componentData.extends.msgType == 'taskWarning') {
      // 项目预警
      messageObj.title = `【${curWf.name}】项目预警`;
    }
    else if (this.componentData.extends.msgType == 'taskMsg') {
      // 任务消息
      messageObj.title = `【${curWf.name}】项目任务`;
    }
    else if (this.componentData.extends.msgType == 'notificationMsg') {
      // 通知消息
      messageObj.title = `【${curWf.name}】项目通知`;
    }

    if (this.componentData.extends.overCondition && this.componentData.extends.overCondition.sentence) {
      messageObj.conditionSentence = this.componentData.extends.overCondition.sentence
    }

    if (this.componentData.extends.msgType == 'taskWarning') {
      // 任务消息生成专门的id用于验证一个任务只发送一条
      messageObj.id = Md5.hashStr(this.tmpComItemId + this.dataRegister.id) as string;
    }
    else {
      messageObj.id = Tools.GetGuid();
    }

    await this.messageSvr.createMessage(messageObj);

  }
}

interface SpaceCharItem {
  index: number;
  code: string;
  bindField?: string;
  tmpComItemId?: string;
  selector?: string;
  addTime?: number;
  addTimeType?: string;
}
